<?php
namespace App\Workerman;

include_once(__DIR__ . '/../../vendor/autoload.php');

use GatewayWorker\Lib\Gateway;
use Workerman\Lib\Timer;
use Curl\Curl as C;

(\Dotenv\Dotenv::createImmutable(__DIR__ . '/../../'))->load();//加载.env文件

/**
 * 主进程不做 redis/mysql 服务
 * Class Events
 * @package App\Workerman
 */
class Events
{
    private static $api = '/api';

    private static $ignoreSymbol = ['\\','/'];

    public static function onWorkerStart($businessWorker)
    {
        Timer::add(5,function (){
            echo 1;
        });
    }

    /**
     * 数据处理
     * @param $client_id
     * @param $message
     */
    public static function onMessage($client_id, $message):void
    {
        $mes = jsonToArray($message);//json
        if ($mes) {
            if(isset($mes['f']) && !empty($mes['f'])) {
                $url = trimList($_ENV['DOMAIN'],self::$ignoreSymbol) . self::$api . '/' . trimList($mes['f'],self::$ignoreSymbol);
            }else{
                $url = trimList($_ENV['DOMAIN'],self::$ignoreSymbol) . self::$api . '/';
            }
            //路由访问规则
            $curl = new C();
            $curl->post($url,[
                'client_id' => $client_id,
                'message' => $mes
            ]);
            $code = $curl->getHttpStatusCode();
            if($code == 200) {
                //成功
//                $curl->response;
                var_dump($curl->response);
            } else {
                Gateway::sendToClient($client_id,toJson([
                    'code' => $code,
                    'message' => '非法请求~'
                ]));
            }
        }
    }

    public static function onConnect($client_id){}

    public static function onWebSocketConnect($client_id, $data){}

    public static function onClose($client_id){}
}
